package ddbs;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import java.io.*;
import java.util.Map;

public class SQLHttpHandler implements HttpHandler {
    Gui gui = null;
    final static String index_html = "index.html";
    final static String result_html = "result.html";

    public SQLHttpHandler(Gui gui2) {
        this.gui = gui2;
    }

    private StringBuffer getFileContent(String filename) {
        StringBuffer html = new StringBuffer();
        String line = null;
        BufferedReader br;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(
                    filename)));
            while ((line = br.readLine()) != null) {
                html.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return html;
    }

    private String handleGet(HttpExchange t, Map<String, Object> params) {
        StringBuffer html = getFileContent(index_html);
        // SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // System.out.println(df.format(new Date()));
        // html = new StringBuffer("hello world\n");
        // html.append(df.format(new Date()));
        return html.toString();
    }

    private String generateResult(String sql, Data d, long time) {
        String html = getFileContent(result_html).toString();
        html = html.replace("<!--${SQL}-->", sql);
        html = html.replace("<!--${TIME}-->", time + "ms");
        html = html.replace("<!--${RESULT}-->", d.generateHtmlTable());
        return html;
    }

    private String handlePost(HttpExchange t, Map<String, Object> params) {
        long timeStart = System.currentTimeMillis();
        String sql = (String) params.get("sql");
        sql = sql.trim();
        for (int i =0; i< 4; ++i) {
            gui.sch.getMgr().getPeer(i).transferSizeS = 0;
            gui.sch.getMgr().getPeer(i).transferSizeR = 0;

        }
        System.out.println("handlePost SQL=" + sql);
        Data d = gui.handleSQL(sql);
        System.out.println("============================================================");
        System.out.println("Result size = " + d.getSize());
        for (int i =0; i< 4; ++i) {
            System.out.println("#"+gui.sch.getMgr().getSelfId()+" send to #"+ i+" size="+gui.sch.getMgr().getPeer(i).transferSizeS);
            System.out.println("#"+gui.sch.getMgr().getSelfId()+" rec from #"+ i+" size="+gui.sch.getMgr().getPeer(i).transferSizeR);
        }
        long timeEnd = System.currentTimeMillis();
        String response = generateResult(sql, d, timeEnd - timeStart);
        return response;
    }

    @SuppressWarnings("unchecked")
    public void handle(HttpExchange t) {
        Map<String, Object> params = (Map<String, Object>) t
                .getAttribute("parameters");
        String response = null;
        if (t.getRequestMethod().equals("GET")) {
            response = handleGet(t, params);
        } else {
            response = handlePost(t, params);
        }
        try {
            t.sendResponseHeaders(200, response.length());
            OutputStream os = t.getResponseBody();
            os.write(response.getBytes());
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
